<?php
namespace components;

class Register
{
	//用于spl_autoload_register
	//自动加载
	static function getFileByNameSpace($rawclass){
		static $namespace = [];
		if(isset($namespace[$rawclass])){
			 require_once($namespace[$rawclass]);
			 return;
		}
		$flag1 = preg_match('/controllers/', $rawclass);
		$flag2 = preg_match('/Controller$/', $rawclass);
		$class = explode('\\',$rawclass);
		$class = PATH_BASE . implode('/', $class);
		if($flag1 && !$flag2) {
			$class .= 'Controller';	
		}
		$class .= '.php';
		if(file_exists($class)){
			$namespace[$rawclass] = $class;
			require_once($class);
			return;
		}else{
			throw new \Exception('file not exists:'.$class);
		}

	}

	static function pokerException($exception){
		self::writer('exception.log.' . date('Y-m-d'),
				'file:'   .$exception->getFile(),
			    'line:'   .$exception->getLine(),
			    'code:'   .$exception->getCode(),
			    'message:'.$exception->getMessage()	    
		);
	}

	static function pokerError($errno ,$errstr,$errfile,$errline){
		self::writer('error.log.' . date('Y-m-d'),
				'file:'   .$errfile,
			    'line:'   .$errline,
			    'code:'   .$errno,
			    'message:'.$errstr	    
		);
	}
	static function writer(){
		$args = func_get_args();
		$filename = array_shift($args);
		array_unshift($args,date('Y-m-d H:i:s'));
		!file_exists(PATH_RUNTIME) && mkdir(PATH_RUNTIME,0777);
		file_put_contents(PATH_RUNTIME . $filename,implode("\t", $args) . "\n",FILE_APPEND);
		if (DEBUG && strpos($filename, 'request.log') === false) {
			\libs\URIProcess::dispatch([ 'filename' => $filename,'debug' => $args]);
		}
	}
}
spl_autoload_register(['components\Register','getFileByNameSpace']);
set_exception_handler(['components\Register','pokerException']);
set_error_handler(['components\Register','pokerError']);
